setwd("E://OneDrive//1-教学//科技论文写作//课件//课上使用的文档//2.9.5-科研绘图//基础知识") #设置工作路径

install.packages("xlsx")  #仅第一次需要运行，安装"xlsx"包
library(xlsx)             #加载"xlsx"包
data <- read.xlsx("data.xlsx", sheetName = "Sheet1" , encoding = "UTF-8") 
                          #变量名 <- read.xlsx("文件名.xlsx", sheetName = "表名，如Sheet1" , encoding = "UTF-8")

data                      #展示加载的数据

library(ggplot2)          #加载"ggplot2"包
ggplot(data)+
  geom_boxplot(aes(x = Treatment, y = Biomass))  #一个简单的箱型图


######################################################
data2 <- read.xlsx("data.xlsx", sheetName = "Sheet2" , encoding = "UTF-8") 
data2

d1 <- rbind(data, data2)
d1

ggplot(d1)+
  geom_boxplot(aes(x = Treatment, y = Biomass)) 


data3 <- read.xlsx("data.xlsx", sheetName = "Sheet3" , encoding = "UTF-8") 
data3

d2_1 <- cbind(data, data3)
d2_1           #未对应，Treatment列重复出现

data3_1 <- data3
data3_1 <- data3_1[order(data3_1$Treatment),]
               #按Treatment排序，使数据与data数据框排序相同
data3_1
d2_2 <- cbind(data, data3_1)
d2_2
d2_2[,-3]      #去除多余的Treatment列


d3_1 <- merge(data, data3, by = "Treatment")
d3_1           #data中每行数据能对应data3中的3个数据

data$re <- rep(c(1:3),2)
data3_2 <- data3
data3_2$re <- rep(c(1:3),2)
d3_3 <- merge(data, data3_2, by = c("Treatment", "re"))
d3_2

##########################################################
mean(data$Biomass)    #只能得到两个处理下的总生物量
Treatment <- c("CK", "T")
Biomass_mean <- data.frame()
for (i in c(1:2)) {
  Biomass_mean[i,1] <- Treatment[i]
  Biomass_mean[i,2] <- mean(data[data$Treatment == Treatment[i], 2])
  Biomass_mean[i,3] <- sd(data[data$Treatment == Treatment[i], 2])
}
Biomass_mean

ggplot(Biomass_mean)+
  geom_pointrange(aes(x = V1, y = V2, ymin = V2-V3, ymax = V2+V3))

###########################################################
if (判断条件) {
  为真时运行
} else {
  为假时运行
}

myfun <- function(df) {
  Fig <- ggplot(df)+
    geom_boxplot(aes(x = Treatment, y = Biomass))  #一个简单的箱型图
  return(Fig)
}
myfun(data)
myfun(data2)

##########################################################
install.packages("RColorBrewer")
library(RColorBrewer)

display.brewer.all(type="seq")  #连续

display.brewer.all(type="div")  #极端

display.brewer.all(type="qual") #离散

brewer.pal(8,"Dark2")[1:5]      #从"Dark2"配色方案中选择前8个颜色中的1-5个

ggplot(data)+
  geom_boxplot(aes(x = Treatment, y = Biomass, fill = Treatment))

ggplot(data)+
  geom_boxplot(aes(x = Treatment, y = Biomass, fill = Treatment))+
  scale_fill_manual(values = brewer.pal(8,"Set1"))